package alogrithm;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/11/5 10:51
 */
public class BuildTree {
    Map<Integer, Integer> indexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;

        for (int i = 0; i < n; ++i) {
            indexMap.put(inorder[i], i);
        }
        return buildTree(preorder, inorder, 0, n - 1, 0, n - 1);
    }

    private TreeNode buildTree(int[] preorder, int[] inorder, int preOrderLeft, int preOrderRight, int inOrderLeft, int inOrderRight) {
        if (preOrderLeft > preOrderRight) {
            return null;
        }
        int inOrderRoot = indexMap.get(preorder[preOrderLeft]);
        TreeNode root = new TreeNode(preorder[preOrderLeft]);
        int sizeLeftSubTree = inOrderRoot - inOrderLeft;
        root.left = buildTree(preorder, inorder, preOrderLeft + 1, preOrderLeft + sizeLeftSubTree, inOrderLeft, inOrderRoot - 1);
        root.right = buildTree(preorder, inorder, preOrderLeft + sizeLeftSubTree + 1, preOrderRight, inOrderRoot + 1, inOrderRight);
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
